package wblog;

import cn.webwheel.DefaultMain;
import cn.webwheel.WebContext;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletModule;
import org.apache.commons.dbutils.QueryRunner;
import wblog.service.QueryRunnerProvider;

public class Main extends DefaultMain {

    Injector injector;

    QueryRunnerProvider queryRunnerProvider;

    @Override
    protected void init() {
        super.init();

        try {
            queryRunnerProvider = new QueryRunnerProvider(servletContext);
        } catch (Exception e) {
            throw new RuntimeException("db init fail", e);
        }

        injector = Guice.createInjector(new MainModule());

        autoMap("wblog.web");
    }

    @Override
    public <T> T createAction(WebContext ctx, Class<T> type) {
        return injector.getInstance(type);
    }

    @Override
    protected void destroy() {
        queryRunnerProvider.dispose();
    }

    class MainModule extends ServletModule {
        @Override
        protected void configureServlets() {
            bind(QueryRunner.class).toProvider(queryRunnerProvider).in(Singleton.class);
        }
    }
}
